﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ShopB2C.Entity;
using ShopB2C.Helper;
using ShopB2C.Parameters;
using ShopB2C.ViewModels;
using ShopB2C.Enums;
using ShopB2C.Export;
using System.Text;

namespace ShopB2C.Controllers.Manager {
    /// <summary>
    /// Classify
    /// </summary>
    public partial class ClassifyController : BaseController {

        public ActionResult ClassifyIndex(string classifyParams) {
            if (_classifyConfig.Where(cc => { return cc.ModuleKey == classifyParams; }).Count() == 0) {
                throw new Exception("错误的模块参数！");
            }

            return RedirectToAction("ClassifyList", new {
                classifyParams = new ClassifyParam() { ModuleKey = classifyParams }.ToString()
            });
        }

        public ActionResult ClassifyList(string classifyParams) {
            this.SiteMapPathAdd("商品分类");

            ClassifyParam cp = Methods.FormatClassifyParams(classifyParams);
            if (string.IsNullOrEmpty(cp.ModuleKey)) {
                throw new Exception("错误的模块参数！");
            }

            ClassifyEntity ce = cp.ParentClassifyId == 0
                ? new ClassifyEntity()
                : _classify.GetClassifyById(cp.ParentClassifyId);

            List<ClassifyEntity> pathList = null;
            if (ce != null) {
                pathList = _classify.GetClassifyByModuleKeyAndPath(ce.ModuleKey,
                    string.Format("{0}-{1}", ce.Path, ce.ClassifyId));
            }

            ViewData["ClassList"] = _classify.GetClassifyByModuleKey(cp.ModuleKey);

            List<ClassifyEntity> classifyList =
                _classify.GetClassifyByModuleKeyAndId(cp.ModuleKey, cp.ParentClassifyId);
            cp.AutoSequence = classifyList != null ? classifyList.Count + 1 : 1;

            ClassifyConfig cc = _classifyConfig.Where(c => { return c.ModuleKey == cp.ModuleKey; }).First();
            return View(new ClassifyViewModel() {
                ModuleName = cc.ModuleName,
                IsAllowHasChild = cc.IsAllowHasChild,
                IsAllowHasProperty = cc.IsAllowHasProperty,
                ClassifyParams = cp,
                Classify = ce,
                ClassifyList = classifyList,
                PathList = pathList
            });
        }

        public ActionResult ClassifyEdit(string classifyParams) {
            this.SiteMapPathAdd("商品分类", Url.Action("ClassifyList", new { classifyParams = classifyParams }));
            this.SiteMapPathAdd("商品分类编辑");

            ClassifyParam cp = Methods.FormatClassifyParams(classifyParams);
            ClassifyEntity ce = cp.ClassifyId == 0
                    ? new ClassifyEntity() { ParentClassifyId = cp.ParentClassifyId }
                    : _classify.GetClassifyById(cp.ClassifyId);

            ce.Sequence = cp.ClassifyId > 0 ? ce.Sequence : cp.AutoSequence;
            cp.ClassifyId = 0;
            cp.AutoSequence = 0;
            ClassifyConfig cc = _classifyConfig.Where(c => { return c.ModuleKey == cp.ModuleKey; }).First();
            return View(new ClassifyViewModel() {
                ModuleName = cc.ModuleName,
                IsAllowHasChild = cc.IsAllowHasChild,
                IsAllowHasProperty = cc.IsAllowHasProperty,
                ClassifyParams = cp,
                Classify = ce,
                ClassifyList = cc.IsAllowHasChild
                    ? _classify.GetClassifyByModuleKey(cp.ModuleKey)
                    : new List<ClassifyEntity>()
            });
        }

        [HttpPost]
        public ActionResult ClassifyEdit(string classifyParams, ClassifyViewModel cvm) {
            ClassifyParam cp = Methods.FormatClassifyParams(classifyParams);
            ClassifyEntity ce = cvm.Classify;

            ce.ModuleKey = cp.ModuleKey;
            if (ce.ClassifyId == 0) {
                _classify.ClassifyAppend(ce);
                cp.AutoSequence++;
            }
            else {
                _classify.ClassifyUpdate(ce);
                cp.AutoSequence = 0;
                cp.ClassifyId = 0;
            }

            return RedirectToAction(ce.ClassifyId == 0 ? "ClassifyEdit" : "ClassifyList", new {
                classifyParams = cp.ToString()
            });
        }

        public ActionResult ClassifyDelete(string classifyParams) {
            ClassifyParam cp = Methods.FormatClassifyParams(classifyParams);
            _classify.ClassifyDelete(cp.ClassifyId);

            cp.ClassifyId = 0;
            return this.RedirectToAction("ClassifyList", new {
                classifyParams = cp.ToString()
            });
        }

        [HttpPost]
        public ActionResult ClassifyEditBatchSeq(string classifyParams, FormCollection fc) {
            _classify.ClassifyBatchUpdateSequence(fc["cbKey"], fc["tbSequence"]);

            ClassifyParam cp = Methods.FormatClassifyParams(classifyParams);
            cp.ClassifyId = 0;

            return this.RedirectToAction("ClassifyList", new {
                classifyParams = cp.ToString()
            });
        }

        public ActionResult ClassifyMenuCreate(string classifyParams) {
            ClassifyParam cp = Methods.FormatClassifyParams(classifyParams);

            new ClassifyMenuHelper(
                _classify.GetClassifyByModuleKey(cp.ModuleKey),
                ConfigHelper.GetValue(ConfigNodeNames.System, "ClassifyMenuCreateUrl")).Create();

            return this.RedirectToAction("ClassifyList", new {
                classifyParams = cp.ToString()
            });
        }

        #region Import Or Export

        public FileResult ClassifyTemplate() {
            return File(
                Classify.GetClassifyTemplateFileStream(), 
                "application/vnd.ms-excel", 
                "ClassifyTemplate.xls");
        }

        public ActionResult ClassifyExport(string classifyParams) {
            this.SiteMapPathAdd("商品分类", Url.Action("ClassifyList", new { classifyParams = classifyParams }));
            this.SiteMapPathAdd("导入导出");

            ClassifyParam cp = Methods.FormatClassifyParams(classifyParams);
            return View(new ClassifyViewModel() {
                ClassifyParams = cp,
                ClassifyList = _classify.GetClassifyByModuleKey(cp.ModuleKey)
            });
        }

        // jquery.form 上传文件返回 json 有问题
        [HttpPost]
        public ContentResult ClassifyImport() {
            StringBuilder sb = new StringBuilder();
            List<string> errorList = Classify.Import(Request.Files["importFile"].InputStream);
            if (errorList.Count < 1) {
                sb.Append("<li>导入成功完成！</li>");
            }
            else {
                foreach (string s in errorList) {
                    sb.AppendFormat("<li>{0}</li>", s);
                }
            }
            return this.Content(sb.ToString());
        }

        [HttpPost]
        public JsonResult ClassifyExport(FormCollection fc) {
            int classifyId = int.Parse(fc["selClassify"]);
            string types = fc["cbExportType"];
            string fileName = fc["tbName"];
            string msg = "error";
            List<string> errorList = new List<string>();

            if (string.IsNullOrEmpty(types)) {
                errorList.Add("必须提供生成的条件，分类，分类特性，分类特性值。");
            }
            if (string.IsNullOrEmpty(fileName)) {
                errorList.Add("必须提供生成下载的文件名称。");
            }

            if (errorList.Count == 0) {
                msg = "sucess";
                errorList.Add("成功生成文件，请点击文件名称旁边链接下载。");
                Session.Add("FileName", fileName);
                Session.Add("FilePath", Classify.Export(errorList, classifyId, types));
            }

            return this.Json(new { Error = errorList, Msg = msg });
        }

        public FileResult DownLoadFile() {
            string filePath = Session["FilePath"].ToString();
            string fileName = Session["FileName"].ToString();

            Session.Remove("FilePath");
            Session.Remove("FileName");

            return File(filePath, "application/vnd.ms-excel", fileName);
        }

        #endregion
    }
}